package ug.co.icom.kyazze.healthticket.mongoHQ;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import ug.co.icom.kyazze.healthticket.LoginActivity;
import ug.co.icom.kyazze.healthticket.data.LoginReturnValue;
import ug.co.icom.kyazze.healthticket.data.QueryBuilder;
import ug.co.icom.kyazze.healthticket.data.User;
import ug.co.icom.kyazze.healthticket.services.ApplicationObject;
import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;

public class MongoHQLogin extends AsyncTask<Object, Void, LoginReturnValue> {
	
	@SuppressWarnings("unused")
	private LoginActivity c;
	@SuppressWarnings("unused")
	private ProgressDialog pd;
	private Context activityContext;

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}
	static BasicDBObject user = null;
	static String OriginalObject = "";
	static String server_output = null;
	static String temp_output = null;
	
	
	
	Locale locale = Locale.getDefault();

	@Override
	protected LoginReturnValue doInBackground(Object... params) {
		LoginReturnValue lrv = new LoginReturnValue();
		activityContext = (Context) params[2];
		ApplicationObject mApplication = (ApplicationObject)activityContext;
		try {
			
			
			String userName =params[0].toString();
			String password =params[1].toString();
			QueryBuilder qb = new QueryBuilder();
			URL url = new URL(qb.buildLoginUrl(userName, password));
			HttpURLConnection conn = (HttpURLConnection) url
					.openConnection();
			conn.setRequestMethod("GET");
			conn.setRequestProperty("Accept", "application/json");

			if (conn.getResponseCode() != 200) {
				throw new RuntimeException("Failed : HTTP error code : "
						+ conn.getResponseCode());
			}

			BufferedReader br = new BufferedReader(new InputStreamReader(
					(conn.getInputStream())));

			//System.out.println("Output from Server .... \n");
			while ((temp_output = br.readLine()) != null) {
				server_output = temp_output;
			}

			// Remove square brackets
			OriginalObject = server_output.substring(1, server_output.length() - 1);

			Object o = com.mongodb.util.JSON.parse(OriginalObject);

			DBObject userObj = (DBObject) o;
			
			User temp = new User();

			//temp.ID = userObj.get("_id").toString();
			temp.PhoneNumber = userObj.get("phonenumber").toString();
			temp.PassCode = userObj.get("passcode").toString();
			temp.FirstName = userObj.get("firstname").toString();
			temp.LastName = userObj.get("lastname").toString();
			temp.OtherNames = userObj.get("othernames").toString();
			temp.Address = userObj.get("address").toString();
			temp.BloodType = userObj.get("bloodtype").toString();
			temp.Female = Boolean.parseBoolean(userObj.get("female").toString());
			temp.DateOfBirth = getDateFromString(userObj.get("dateofbirth").toString());
			temp.Email = userObj.get("email").toString();
			
			lrv.user = temp;

		}catch (Exception e) {
			e.getMessage();
			mApplication.setReturnValue(false);
			lrv.returnValue = false;
			return lrv;
		}
		
		mApplication.setReturnValue(true);
		lrv.returnValue = true;
		return lrv;
	}

	@Override
	protected void onPostExecute(LoginReturnValue result) {
		LoginActivity.dismissDialog();
		
		super.onPostExecute(result);
	}

	
	private Date getDateFromString(String dateReceived) {
		SimpleDateFormat  format = new SimpleDateFormat("dd-MM-yyyy", locale);  
		try {  
		    Date date = format.parse(dateReceived);  
		    return date;  
		} catch (Exception e) {  
		    return new Date();
		}
	}
}
